//
//  SubmitTowerViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/17/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import SVProgressHUD
import AVOSCloud

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}


class SubmitTowerViewController: RootViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UIScrollViewDelegate {

    
    @IBOutlet weak var contentHeight: NSLayoutConstraint!
    
    @IBOutlet weak var line1: NSLayoutConstraint!
    @IBOutlet weak var line2: NSLayoutConstraint!
    @IBOutlet weak var line3: NSLayoutConstraint!
    @IBOutlet weak var line4: NSLayoutConstraint!
    @IBOutlet weak var line5: NSLayoutConstraint!
    @IBOutlet weak var line6: NSLayoutConstraint!
    @IBOutlet weak var line7: NSLayoutConstraint!
    
    
    @IBOutlet weak var gaolouTextField: UITextField!
    @IBOutlet weak var lougaoTextField: UITextField!
    @IBOutlet weak var loucengTextField: UITextField!
    @IBOutlet weak var timeTextField: UITextField!
    @IBOutlet weak var useTextField: UITextField!
    
    @IBOutlet weak var cityButton: UIButton!
    @IBOutlet weak var statusButton: UIButton!
    
    @IBOutlet weak var pickerView: UIPickerView!
    @IBOutlet weak var buttonView: UIView!
    
    @IBOutlet weak var pickerViewToBottom: NSLayoutConstraint!
    
    let height = UIScreen.main.bounds.height-64+1
    
//    var regions:[Region]?
    
//    var tempCity: City?
//    var confirmCity: City?
    
    var countrys:[Country]?
    
    var temAllCity: AllCity?
    var confirmAllCity: AllCity?
    
    var temCountry: Country?
    var confirmCountry: Country?
    
    var confirmStatus: String?
    
    var alertController: UIAlertController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        line1.constant = 0.5
        line2.constant = 0.5
        line3.constant = 0.5
        line4.constant = 0.5
        line5.constant = 0.5
        line6.constant = 0.5
        line7.constant = 0.5
        contentHeight.constant = height
        
//        regions = DataCenter.sharedInstance.commonRegin
//        regions?.removeLast()
        
        pickerViewToBottom.constant = -320
    }
    
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(ReplyTopViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ReplyTopViewController.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    func resinFirst() {
        gaolouTextField.resignFirstResponder()
        lougaoTextField.resignFirstResponder()
        loucengTextField.resignFirstResponder()
        timeTextField.resignFirstResponder()
        useTextField.resignFirstResponder()
    }
    
    @IBAction func buttonClicked(_ sender: UIButton) {
        resinFirst()
        if sender.tag == 400 { // 选择区域
            alertController?.dismiss(animated: false, completion: {
                
            })
            
            pickerViewToBottom.constant = 0
            pickerView.becomeFirstResponder()
            UIView.animate(withDuration: 0.2, animations: {
                self.pickerView.layoutIfNeeded()
                self.buttonView.layoutIfNeeded()
            })
        } else if sender.tag == 700 { // 选择状态
            pickerDismiss()
            if alertController == nil {
                alertController = UIAlertController(title: "", message: "请选择状态", preferredStyle: .actionSheet)
                let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                
                let alertAction = {(action :UIAlertAction) in
                    let name = action.title
                    self.statusButton.setTitle(name, for: UIControlState())
                    self.confirmStatus = name
                }
                
                let confirmAction1 = UIAlertAction(title: "建成", style: .default, handler: alertAction)
                let confirmAction2 = UIAlertAction(title: "封顶", style: .default, handler: alertAction)
                let confirmAction3 = UIAlertAction(title: "在建", style: .default, handler: alertAction)
//                let confirmAction4 = UIAlertAction(title: "预备", style: .Default, handler: alertAction)
                let confirmAction5 = UIAlertAction(title: "规划", style: .default, handler: alertAction)
                let confirmAction6 = UIAlertAction(title: "搁置", style: .default, handler: alertAction)
                
                alertController!.addAction(cancelAction)
                alertController!.addAction(confirmAction1)
                alertController!.addAction(confirmAction2)
                alertController!.addAction(confirmAction3)
//                alertController!.addAction(confirmAction4)
                alertController!.addAction(confirmAction5)
                alertController!.addAction(confirmAction6)
            }
            self.present(alertController!, animated: true, completion: nil)
        }
    }
    
    
    @IBAction func submitClicked(_ sender: UIBarButtonItem) {
        resinFirst()
        pickerDismiss()
        alertController?.dismiss(animated: false, completion: {
            
        })
        
        if (gaolouTextField.text!.isEmpty) {
            SVProgressHUD.showError(withStatus: "请输入楼名")
            return
        } else if lougaoTextField.text!.isEmpty {
            SVProgressHUD.showError(withStatus: "请输入楼高")
            return
        } else if loucengTextField.text!.isEmpty {
            SVProgressHUD.showError(withStatus: "请输入楼层数")
            return
        } else if timeTextField.text!.isEmpty {
            SVProgressHUD.showError(withStatus: "请输入建成时间")
            return
        } else if useTextField.text!.isEmpty {
            SVProgressHUD.showError(withStatus: "请输入用途")
            return
        }
        
        if confirmStatus == nil {
            SVProgressHUD.showError(withStatus: "请选择状态")
            return
        }
        if confirmAllCity == nil {
            SVProgressHUD.showError(withStatus: "请选择区域")
            return
        }
        
        SVProgressHUD.show()
        
        let tower = Tower()
        tower.name = gaolouTextField.text
        tower.allCity = confirmAllCity
        tower.countryName = confirmCountry?.name
        tower.height = Float(lougaoTextField.text!)!
        tower.floor = Int(loucengTextField.text!)!
        tower.timeFinish = Int(timeTextField.text!)!
        tower.purpose = useTextField.text
        tower.status = confirmStatus
        tower.isShow = false
        tower.user = AVUser.current()
        tower.descriptions = ""
        
        tower.saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                self.navigationController?.popViewController(animated: true)
                SVProgressHUD.showSuccess(withStatus: "提交成功，等待审核，预计12小时内生效")
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription)
            }
        }
    }
    
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return (countrys?.count)!
        } else {
            let index = pickerView.selectedRow(inComponent: 0)
            let citys = countrys![index].allCitys
            return (citys?.count)!
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return countrys![row].name
        } else {
            let index = pickerView.selectedRow(inComponent: 0)
            let citys = countrys![index].allCitys
            if citys?.count < row {
                return ""
            }
            return citys![row].name
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            pickerView.reloadComponent(1)
        } else if component == 1 {
            let index = pickerView.selectedRow(inComponent: 0)
            let citys = countrys![index].allCitys
            temAllCity = citys![row]
            temCountry = countrys![index]
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (textField.text?.characters.count)! + string.characters.count > 30 {
            SVProgressHUD.showError(withStatus: "最多输入30个字")
            return false
        }
        return true
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
         pickerDismiss()
        return true
    }
    
    @IBAction func cancelCliked(_ sender: UIButton) {
        pickerDismiss()
        
    }
  
    @IBAction func confirmCliked(_ sender: UIButton) {
        pickerDismiss()
        confirmAllCity = temAllCity
        confirmCountry = temCountry
        if confirmAllCity != nil {
            cityButton.setTitle(confirmAllCity?.name, for: UIControlState())
        }
    }
    
    @IBAction func gestureTap(_ sender: UITapGestureRecognizer) {
        pickerDismiss()
        resinFirst()
    }
    
    func pickerDismiss() {
        pickerViewToBottom.constant = -320
        pickerView.resignFirstResponder()
        UIView.animate(withDuration: 0.2, animations: {
            self.pickerView.layoutIfNeeded()
            self.buttonView.layoutIfNeeded()
        })
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        pickerDismiss()
    }
    
    
    // MARK: NSNotificationCenter
    
    func keyboardDidShow(_ noti: Notification) {
        
        let keyBordHeight = ((noti as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
        
        contentHeight.constant = height+keyBordHeight
    }
    
    func keyboardDidHide(_ noti: Notification) {
        
        contentHeight.constant = height
    }
}








